<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><meta name="generator" content="Hexo 3.9.0"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png"><link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico"><link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico"><link rel="mask-icon" href="/images/logo.svg" color="#222"><meta name="baidu-site-verification" content="WIIeufYjj6"><link rel="stylesheet" href="/css/main.css"><link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css"><script id="hexo-configurations">var NexT=window.NexT||{},CONFIG={hostname:new URL("http://winddoing.github.io").hostname,root:"/",scheme:"Mist",version:"7.7.0",exturl:!1,sidebar:{position:"right",width:300,display:"post",padding:18,offset:12,onmobile:!1},copycode:{enable:!0,show_result:!1,style:"flat"},back2top:{enable:!0,sidebar:!1,scrollpercent:!1},bookmark:{enable:!1,color:"#222",save:"auto"},fancybox:!1,mediumzoom:!1,lazyload:!1,pangu:!1,comments:{style:"tabs",active:"livere",storage:!0,lazyload:!1,nav:null,activeClass:"livere"},algolia:{appID:"OWFNL0AG1F",apiKey:"796a4b50e2653330cac4e0f8b1f8ade4",indexName:"winddoing",hits:{per_page:10},labels:{input_placeholder:"输入关键词",hits_empty:"没有找到与「${query}」相关的内容",hits_stats:"${hits} 条相关记录，共耗时 ${time} ms"}},localsearch:{enable:!0,trigger:"auto",top_n_per_article:1,unescape:!1,preload:!1},path:"search.xml",motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}}}</script><meta name="description" content="Linux系统下的多线程遵循POSIX线程接口，称为pthread。编写Linux下的多线程程序，需要使用头文件&amp;lt;pthread.h&amp;gt;，链接时需要使用库libpthread.so。Linux下pthread的实现是通过系统调用clone()来实现的。 1gcc pthread_create.c -o pthread_create -lpthread  pthread12345$ldd"><meta name="keywords" content="线程"><meta property="og:type" content="article"><meta property="og:title" content="线程--pthread"><meta property="og:url" content="http://winddoing.github.io/post/8868.html"><meta property="og:site_name" content="Winddoing&#39;s Blog"><meta property="og:description" content="Linux系统下的多线程遵循POSIX线程接口，称为pthread。编写Linux下的多线程程序，需要使用头文件&amp;lt;pthread.h&amp;gt;，链接时需要使用库libpthread.so。Linux下pthread的实现是通过系统调用clone()来实现的。 1gcc pthread_create.c -o pthread_create -lpthread  pthread12345$ldd"><meta property="og:locale" content="zh-CN"><meta property="og:updated_time" content="2020-07-04T09:34:15.244Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="线程--pthread"><meta name="twitter:description" content="Linux系统下的多线程遵循POSIX线程接口，称为pthread。编写Linux下的多线程程序，需要使用头文件&amp;lt;pthread.h&amp;gt;，链接时需要使用库libpthread.so。Linux下pthread的实现是通过系统调用clone()来实现的。 1gcc pthread_create.c -o pthread_create -lpthread  pthread12345$ldd"><link rel="canonical" href="http://winddoing.github.io/post/8868.html"><script id="page-configurations">CONFIG.page={sidebar:"",isHome:!1,isPost:!0}</script><link rel="stylesheet" href="//cdn.jsdelivr.net/gh/theme-next/theme-next-needmoreshare2@1/needsharebutton.min.css"><style>#needsharebutton-postbottom{cursor:pointer;height:26px;margin-top:10px;position:relative}#needsharebutton-postbottom .btn{border:1px solid $btn-default-border-color;border-radius:3px;display:initial;padding:1px 4px}</style><title>线程--pthread | Winddoing's Blog</title><script>var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?38fa95924670925239ef842cb0c8722b";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-header,.use-motion .comments,.use-motion .menu-item,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript></head><body itemscope itemtype="http://schema.org/WebPage"><div class="container use-motion"><div class="headband"></div><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-container"><div class="site-meta"><div><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">Winddoing's Blog</span><span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">Follow Excellent, Success will Chase you</h1></div><div class="site-nav-toggle"><div class="toggle" aria-label="切换导航栏"><span class="toggle-line toggle-line-first"></span><span class="toggle-line toggle-line-middle"></span><span class="toggle-line toggle-line-last"></span></div></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-fw fa-home"></i> 首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i> 标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i> 分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i> 归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i> 关于</a></li><li class="menu-item menu-item-search"><a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i> 搜索</a></li></ul></nav><div class="site-search"><div class="popup search-popup"><div class="search-header"><span class="search-icon"><i class="fa fa-search"></i></span><div class="search-input-container"> <input autocomplete="off" autocorrect="off" autocapitalize="none" placeholder="搜索..." spellcheck="false" type="text" id="search-input"></div><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span></div><div id="search-result"></div></div><div class="search-pop-overlay"></div></div></div></header><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span>0%</span></div><main class="main"><div class="main-inner"><div class="content-wrap"><div class="content"><div class="posts-expand"><article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN"><link itemprop="mainEntityOfPage" href="http://winddoing.github.io/post/8868.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/images/Winddoing.jpg"><meta itemprop="name" content="Winddoing"><meta itemprop="description" content="失败缘于忽视细处，成功始于重视小事。"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Winddoing's Blog"></span><header class="post-header"><h2 class="post-title" itemprop="name headline"> 线程--pthread</h2><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2018-09-29 13:53:00" itemprop="dateCreated datePublished" datetime="2018-09-29T13:53:00+08:00">2018-09-29</time></span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/程序设计/" itemprop="url" rel="index"><span itemprop="name">程序设计</span></a></span></span><span id="/post/8868.html" class="post-meta-item leancloud_visitors" data-flag-title="线程--pthread" title="阅读次数"><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span class="leancloud-visitors-count"></span></span><span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span id="busuanzi_value_page_pv"></span></span><br><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i></span> <span class="post-meta-item-text">本文字数：</span> <span>11k</span></span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="fa fa-clock-o"></i></span> <span class="post-meta-item-text">阅读时长 &asymp;</span> <span>10 分钟</span></span></div></header><div class="post-body" itemprop="articleBody"><p>Linux系统下的多线程遵循<code>POSIX线程</code>接口，称为<code>pthread</code>。编写Linux下的多线程程序，需要使用头文件<code>&lt;pthread.h&gt;</code>，链接时需要使用库libpthread.so。Linux下pthread的实现是通过系统调用<code>clone()</code>来实现的。</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gcc pthread_create.c -o pthread_create -lpthread</span><br></pre></td></tr></table></figure><ul><li>pthread<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ldd pthread_create</span><br><span class="line">	linux-vdso.so<span class="number">.1</span> (<span class="number">0x00007fff45dfe000</span>)</span><br><span class="line">	libpthread.so<span class="number">.0</span> =&gt; /lib/x86_64-linux-gnu/libpthread.so<span class="number">.0</span> (<span class="number">0x00007f5a42a08000</span>)</span><br><span class="line">	libc.so<span class="number">.6</span> =&gt; /lib/x86_64-linux-gnu/libc.so<span class="number">.6</span> (<span class="number">0x00007f5a42617000</span>)</span><br><span class="line">	/lib64/ld-linux-x86<span class="number">-64.</span>so<span class="number">.2</span> (<span class="number">0x00007f5a42e29000</span>)</span><br></pre></td></tr></table></figure></li></ul><a id="more"></a><h2 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h2><p><code>进程</code>是程序执行时的一个<code>实例</code>，即它是程序已经执行到何种程度的数据结构的汇集。从内核的观点看，进程的目的就是担当<code>分配系统资源</code>（CPU时间、内存等）的基本单位。</p><p><code>线程</code>是进程的一个<code>执行流</code>，是CPU调度和分派的基本单位，它是比进程更小的能独立运行的基本单位。一个进程由几个线程组成（拥有很多相对独立的执行流的用户程序共享应用程序的大部分数据结构），线程与同属一个进程的其他的线程共享进程所拥有的全部资源。</p><blockquote><p>“进程——资源分配的最小单位，线程——程序执行的最小单位”</p></blockquote><blockquote><p>进程有独立的地址空间，线程没有单独的地址空间（同一进程内的线程共享进程的地址空间）</p></blockquote><p>优点：</p><ul><li>提高应用程序响应。这对图形界面的程序尤其有意义，当一个操作耗时很长时，整个系统都会等待这个操作，此时程序不会响应键盘、鼠标、菜单的操作，而使用多线程技术，将耗时长的操作（time consuming）置于一个新的线程，可以避免这种尴尬的情况。</li><li>使多CPU系统更加有效。操作系统会保证当线程数不大于CPU数目时，不同的线程运行于不同的CPU上。</li><li>改善程序结构。一个既长又复杂的进程可以考虑分为多个线程，成为几个独立或半独立的运行部分，这样的程序会利于理解和修改。</li></ul><h2 id="使用多线程的理由"><a href="#使用多线程的理由" class="headerlink" title="使用多线程的理由"></a>使用多线程的理由</h2><ol><li><p>理由之一是和进程相比，它是一种非常”节俭”的多任务操作方式。我们知道，在Linux系统下，启动一个新的进程必须分配给它独立的地址空间，建立众多的数据表来维护它的代码段、堆栈段和数据段，这是一种”昂贵”的多任务工作方式。而运行于一个进程中的多个线程，它们彼此之间使用相同的地址空间，共享大部分数据，<code>启动一个线程所花费的空间远远小于启动一个进程所花费的空间</code>，而且，<code>线程间彼此切换所需的时间也远远小于进程间切换所需要的时间</code>。据统计，总的说来，一个进程的开销大约是一个线程开销的<code>30倍</code>左右，当然，在具体的系统上，这个数据可能会有较大的区别。</p></li><li><p>理由之二是线程间方便的<code>通信机制</code>。对不同进程来说，它们具有独立的数据空间，要进行数据的传递只能通过通信的方式进行，这种方式不仅费时，而且很不方便。线程则不然，由于同一进程下的线程之间共享数据空间，所以一个线程的数据可以直接为其它线程所用，这不仅快捷，而且方便。当然，数据的共享也带来其他一些问题，有的变量不能同时被两个线程所修改，有的子程序中声明为static的数据更有可能给多线程程序带来灾难性的打击，这些正是编写多线程程序时最需要注意的地方。</p></li></ol><p>从函数调用上来说，进程创建使用<code>fork()</code>操作；线程创建使用<code>clone()</code>操作。Richard Stevens大师这样说过：</p><blockquote><p>fork is expensive. Memory is copied from the parent to the child, all descriptors are duplicated in the child, and so on. Current implementations use a technique called copy-on-write, which avoids a copy of the parent’s data space to the child until the child needs its own copy. But, regardless of this optimization, fork is expensive.</p></blockquote><blockquote><p>IPC is required to pass information between the parent and child after the fork. Passing information from the parent to the child before the fork is easy, since the child starts with a copy of the parent’s data space and with a copy of all the parent’s descriptors. But, returning information from the child to the parent takes more work.</p></blockquote><blockquote><p>Threads help with both problems. Threads are sometimes called lightweight processes since a thread is “lighter weight” than a process. That is, thread creation can be 10–100 times faster than process creation.</p></blockquote><blockquote><p>All threads within a process share the same global memory. This makes the sharing of information easy between the threads, but along with this simplicity comes the problem of synchronization.</p></blockquote><h2 id="pthread接口"><a href="#pthread接口" class="headerlink" title="pthread接口"></a>pthread接口</h2><blockquote><p><code>#include &lt;pthread.h&gt;</code> #/usr/include/pthread.h</p></blockquote><h3 id="pthread-create"><a href="#pthread-create" class="headerlink" title="pthread_create"></a>pthread_create</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Create a new thread, starting with execution of START-ROUTINE</span></span><br><span class="line"><span class="comment">   getting passed ARG.  Creation attributed come from ATTR.  The new</span></span><br><span class="line"><span class="comment">   handle is stored in *NEWTHREAD.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_create</span> <span class="params">(<span class="keyword">pthread_t</span> *__restrict __newthread,</span></span></span><br><span class="line"><span class="function"><span class="params">               <span class="keyword">const</span> <span class="keyword">pthread_attr_t</span> *__restrict __attr,</span></span></span><br><span class="line"><span class="function"><span class="params">               <span class="keyword">void</span> *(*__start_routine) (<span class="keyword">void</span> *),</span></span></span><br><span class="line"><span class="function"><span class="params">               <span class="keyword">void</span> *__restrict __arg)</span> __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">3</span>))</span></span>;</span><br></pre></td></tr></table></figure><p>用于创建一个线程，成功返回0，否则返回Exxx（为正数）。</p><h3 id="pthread-exit"><a href="#pthread-exit" class="headerlink" title="pthread_exit"></a>pthread_exit</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Terminate calling thread.</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">   The registered cleanup handlers are called via exception handling</span></span><br><span class="line"><span class="comment">   so we cannot mark this function with __THROW.*/</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">void</span> <span class="title">pthread_exit</span> <span class="params">(<span class="keyword">void</span> *__retval)</span> __<span class="title">attribute__</span> <span class="params">((__noreturn__))</span></span>;</span><br></pre></td></tr></table></figure><p>用于终止线程，可以指定返回值，以便其他线程通过pthread_join函数获取该线程的返回值。</p><h3 id="pthread-join"><a href="#pthread-join" class="headerlink" title="pthread_join"></a>pthread_join</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Make calling thread wait for termination of the thread TH.  The</span></span><br><span class="line"><span class="comment">   exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN</span></span><br><span class="line"><span class="comment">   is not NULL.</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">   This function is a cancellation point and therefore not marked with</span></span><br><span class="line"><span class="comment">   __THROW.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_join</span> <span class="params">(<span class="keyword">pthread_t</span> __th, <span class="keyword">void</span> **__thread_return)</span></span>;</span><br></pre></td></tr></table></figure><blockquote><p>以<code>阻塞</code>的方式等待thread指定的线程结束。当函数返回时，被等待线程的资源被收回。如果线程已经结束，那么该函数会立即返回。并且thread指定的线程必须是joinable的。</p></blockquote><p>作用：</p><ul><li>主线程等待子线程的终止</li><li>在子线程调用了<code>pthread_join()`</code>方法后面的代码，只有等到子线程结束了才能执行。</li></ul><h3 id="pthread-detach"><a href="#pthread-detach" class="headerlink" title="pthread_detach"></a>pthread_detach</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Indicate that the thread TH is never to be joined with PTHREAD_JOIN.</span></span><br><span class="line"><span class="comment">   The resources of TH will therefore be freed immediately when it</span></span><br><span class="line"><span class="comment">   terminates, instead of waiting for another thread to perform PTHREAD_JOIN</span></span><br><span class="line"><span class="comment">   on it.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_detach</span> <span class="params">(<span class="keyword">pthread_t</span> __th)</span> __THROW</span>;</span><br></pre></td></tr></table></figure><p>用于是指定线程变为分离状态，就像进程脱离终端而变为后台进程类似。成功返回0，否则返回Exxx（为正数）。变为分离状态的线程，如果线程退出，它的所有资源将全部释放。而如果不是分离状态，线程必须保留它的线程ID，退出状态直到其它线程对它调用了pthread_join。</p><h3 id="pthread-self"><a href="#pthread-self" class="headerlink" title="pthread_self"></a>pthread_self</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Obtain the identifier of the current thread.  */</span>                             </span><br><span class="line"><span class="function"><span class="keyword">extern</span> pthread_t <span class="title">pthread_self</span> <span class="params">(<span class="keyword">void</span>)</span> __THROW __<span class="title">attribute__</span> <span class="params">((__const__))</span></span>;</span><br></pre></td></tr></table></figure><p>获取线程自身的ID，该id由线程库维护，其id空间是各个进程独立的（即不同进程中的线程可能有相同的id）。</p><ul><li>比较两个线程ID<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compare two thread identifiers.  */</span>                                  </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_equal</span> <span class="params">(<span class="keyword">pthread_t</span> __thread1, <span class="keyword">pthread_t</span> __thread2)</span>     </span></span><br><span class="line"><span class="function">  __THROW __<span class="title">attribute__</span> <span class="params">((__const__))</span></span>;</span><br></pre></td></tr></table></figure></li></ul><h3 id="线程属性"><a href="#线程属性" class="headerlink" title="线程属性"></a>线程属性</h3><p>线程属性结构体<code>pthread_attr_t</code></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span>&#123;</span></span><br><span class="line">    <span class="keyword">int</span> etachstate;     <span class="comment">//线程的分离状态</span></span><br><span class="line">    <span class="keyword">int</span> schedpolicy;    <span class="comment">//线程的调度策略</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span>　<span class="title">sched</span> <span class="title">schedparam</span>;</span><span class="comment">//线程的调度参数</span></span><br><span class="line">    <span class="keyword">int</span> inheritsched;   <span class="comment">//线程的继承性</span></span><br><span class="line">    <span class="keyword">int</span> scope;          <span class="comment">//线程的作用域</span></span><br><span class="line">    <span class="keyword">size_t</span> guardsize;   <span class="comment">//线程栈末尾的警戒缓冲区大小</span></span><br><span class="line">    <span class="keyword">int</span> stackaddr_set;  <span class="comment">//线程栈的设置</span></span><br><span class="line">    <span class="keyword">void</span>* stackaddr;    <span class="comment">//线程栈的启始位置</span></span><br><span class="line">    <span class="keyword">size_t</span> stacksize;   <span class="comment">//线程栈大小</span></span><br><span class="line">&#125;<span class="keyword">pthread_attr_t</span>;</span><br></pre></td></tr></table></figure><ul><li>操作接口函数：</li></ul><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Initialize thread attribute *ATTR with default attributes                          </span></span><br><span class="line"><span class="comment">   (detachstate is PTHREAD_JOINABLE, scheduling policy is SCHED_OTHER,                </span></span><br><span class="line"><span class="comment">    no user-provided stack).  */</span>                                                      </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_attr_init</span> <span class="params">(<span class="keyword">pthread_attr_t</span> *__attr)</span> __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;        </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Destroy thread attribute *ATTR.  */</span>                                                </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_attr_destroy</span> <span class="params">(<span class="keyword">pthread_attr_t</span> *__attr)</span>                              </span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;                                                         </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Get detach state attribute.  */</span>                                                    </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_attr_getdetachstate</span> <span class="params">(<span class="keyword">const</span> <span class="keyword">pthread_attr_t</span> *__attr,                 </span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">int</span> *__detachstate)</span>                                               </span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">2</span>))</span></span>;                                                      </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Set detach state attribute.  */</span>                                                    </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_attr_setdetachstate</span> <span class="params">(<span class="keyword">pthread_attr_t</span> *__attr,                       </span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">int</span> __detachstate)</span>                                                </span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br></pre></td></tr></table></figure><h3 id="线程之间互斥"><a href="#线程之间互斥" class="headerlink" title="线程之间互斥"></a>线程之间互斥</h3><p>互斥锁：</p><blockquote><p>使用互斥锁（互斥）可以使线程按顺序执行。通常，互斥锁通过确保一次只有一个线程执行代码的临界段来同步多个线程。互斥锁还可以保护单线程代码。</p></blockquote><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Mutex handling.  */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* Initialize a mutex.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_init</span> <span class="params">(<span class="keyword">pthread_mutex_t</span> *__mutex,</span></span></span><br><span class="line"><span class="function"><span class="params">                   <span class="keyword">const</span> <span class="keyword">pthread_mutexattr_t</span> *__mutexattr)</span></span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Destroy a mutex.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_destroy</span> <span class="params">(<span class="keyword">pthread_mutex_t</span> *__mutex)</span></span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Try locking a mutex.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_trylock</span> <span class="params">(<span class="keyword">pthread_mutex_t</span> *__mutex)</span></span></span><br><span class="line"><span class="function">     __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Lock a mutex.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_lock</span> <span class="params">(<span class="keyword">pthread_mutex_t</span> *__mutex)</span></span></span><br><span class="line"><span class="function">     __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Unlock a mutex.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_unlock</span> <span class="params">(<span class="keyword">pthread_mutex_t</span> *__mutex)</span></span></span><br><span class="line"><span class="function">     __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Get the priority ceiling of MUTEX.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_getprioceiling</span> <span class="params">(<span class="keyword">const</span> <span class="keyword">pthread_mutex_t</span> *</span></span></span><br><span class="line"><span class="function"><span class="params">                     __restrict __mutex,</span></span></span><br><span class="line"><span class="function"><span class="params">                     <span class="keyword">int</span> *__restrict __prioceiling)</span></span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">2</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Set the priority ceiling of MUTEX to PRIOCEILING, return old</span></span><br><span class="line"><span class="comment">   priority ceiling value in *OLD_CEILING.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_mutex_setprioceiling</span> <span class="params">(<span class="keyword">pthread_mutex_t</span> *__restrict __mutex,</span></span></span><br><span class="line"><span class="function"><span class="params">                     <span class="keyword">int</span> __prioceiling,</span></span></span><br><span class="line"><span class="function"><span class="params">                     <span class="keyword">int</span> *__restrict __old_ceiling)</span></span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">3</span>))</span></span>;</span><br></pre></td></tr></table></figure><p>临界资源保护：</p><ol><li>声明<code>pthread_mutex_t</code>类型的变量，并初始化<code>pthread_mutex_init</code></li><li>对临界资源加锁<code>pthread_mutex_lock</code></li><li>其他操作（Do something）</li><li>对临界资源解锁<code>pthread_mutex_unlock</code></li></ol><h3 id="线程同步"><a href="#线程同步" class="headerlink" title="线程同步"></a>线程同步</h3><p>信号量：</p><blockquote><p>使用条件变量（信号量）可以以原子方式阻塞线程，直到某个特定条件为真为止。条件变量始终与互斥锁一起使用。对条件的测试是在互斥锁（互斥）的保护下进行的。如果条件为假，线程通常会基于条件变量阻塞，并以原子方式释放等待条件变化的互斥锁。</p></blockquote><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Functions for handling conditional variables.  */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* Initialize condition variable COND using attributes ATTR, or use</span></span><br><span class="line"><span class="comment">   the default values if later is NULL.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_cond_init</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__restrict __cond,</span></span></span><br><span class="line"><span class="function"><span class="params">                  <span class="keyword">const</span> <span class="keyword">pthread_condattr_t</span> *__restrict __cond_attr)</span></span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Destroy condition variable COND.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_cond_destroy</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__cond)</span></span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Wake up one thread waiting for condition variable COND.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_cond_signal</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__cond)</span></span></span><br><span class="line"><span class="function">     __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Wake up all threads waiting for condition variables COND.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_cond_broadcast</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__cond)</span></span></span><br><span class="line"><span class="function">     __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Wait for condition variable COND to be signaled or broadcast.</span></span><br><span class="line"><span class="comment">   MUTEX is assumed to be locked before.</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">   This function is a cancellation point and therefore not marked with</span></span><br><span class="line"><span class="comment">   __THROW.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_cond_wait</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__restrict __cond,</span></span></span><br><span class="line"><span class="function"><span class="params">                  <span class="keyword">pthread_mutex_t</span> *__restrict __mutex)</span></span></span><br><span class="line"><span class="function">     __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">2</span>))</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Wait for condition variable COND to be signaled or broadcast until</span></span><br><span class="line"><span class="comment">   ABSTIME.  MUTEX is assumed to be locked before.  ABSTIME is an</span></span><br><span class="line"><span class="comment">   absolute time specification; zero is the beginning of the epoch</span></span><br><span class="line"><span class="comment">   (00:00:00 GMT, January 1, 1970).</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">   This function is a cancellation point and therefore not marked with</span></span><br><span class="line"><span class="comment">   __THROW.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_cond_timedwait</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__restrict __cond,</span></span></span><br><span class="line"><span class="function"><span class="params">                   <span class="keyword">pthread_mutex_t</span> *__restrict __mutex,</span></span></span><br><span class="line"><span class="function"><span class="params">                   <span class="keyword">const</span> struct timespec *__restrict __abstime)</span></span></span><br><span class="line"><span class="function">     __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>))</span></span>;</span><br></pre></td></tr></table></figure><p><code>pthread_cond_wait</code>用于等待某个特定的条件为真，<code>pthread_cond_signal</code>用于通知阻塞的线程某个特定的条件为真了。在调用者两个函数之前需要声明一个<code>pthread_cond_t</code>类型的变量，用于这两个函数的参数。</p><blockquote><p><code>pthread_cond_wait</code>只是唤醒等待某个条件变量的一个线程。如果需要唤醒所有等待某个条件变量的线程，需要调用：<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_broadcast</span> <span class="params">(<span class="keyword">pthread_cond_t</span> *__cond)</span></span></span><br></pre></td></tr></table></figure><p></p></blockquote><h3 id="pthread-barrier-xxx"><a href="#pthread-barrier-xxx" class="headerlink" title="pthread_barrier_xxx"></a>pthread_barrier_xxx</h3><p>线程同步，<code>pthread_barrier_*</code>其实只做且只能做一件事，就是充当栏杆（barrier意为栏杆)。形象的说就是把先后到达的多个线程挡在同一栏杆前，直到所有线程到齐，然后撤下栏杆同时放行。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Initialize BARRIER with the attributes in ATTR.  The barrier is        </span></span><br><span class="line"><span class="comment">   opened when COUNT waiters arrived.  */</span>                                 </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_barrier_init</span> <span class="params">(<span class="keyword">pthread_barrier_t</span> *__restrict __barrier,</span></span></span><br><span class="line"><span class="function"><span class="params">                 <span class="keyword">const</span> <span class="keyword">pthread_barrierattr_t</span> *__restrict                  </span></span></span><br><span class="line"><span class="function"><span class="params">                 __attr, <span class="keyword">unsigned</span> <span class="keyword">int</span> __count)</span>                            </span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;                                             </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Destroy a previously dynamically initialized barrier BARRIER.  */</span>      </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_barrier_destroy</span> <span class="params">(<span class="keyword">pthread_barrier_t</span> *__barrier)</span>         </span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;                                             </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Wait on barrier BARRIER.  */</span>                                           </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_barrier_wait</span> <span class="params">(<span class="keyword">pthread_barrier_t</span> *__barrier)</span>            </span></span><br><span class="line"><span class="function">     __THROWNL __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;</span><br></pre></td></tr></table></figure><ol><li>init函数负责指定要等待的线程个数</li><li>wait()函数由每个线程主动调用，它告诉栏杆“我到起跑线前了”。<ul><li>wait(）执行末尾栏杆会检查是否所有人都到栏杆前了</li><li>如果是，栏杆就消失所有线程继续执行下一句代码</li><li>如果不是，则所有已到wait()的线程等待，剩下没执行到wait()的线程继续执行</li></ul></li><li>destroy函数释放init申请的资源。</li></ol><p>应用场景：</p><blockquote><p>比如A和B两人相约在某一个地点C集合去打猎，A和B都知道地方C，但是他们到达的时间不确定，因此谁先到就需要在C点等。</p></blockquote><h3 id="pthread-once"><a href="#pthread-once" class="headerlink" title="pthread_once"></a>pthread_once</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Guarantee that the initialization function INIT_ROUTINE will be called</span></span><br><span class="line"><span class="comment">   only once, even if pthread_once is executed several times with the     </span></span><br><span class="line"><span class="comment">   same ONCE_CONTROL argument. ONCE_CONTROL must point to a static or     </span></span><br><span class="line"><span class="comment">   extern variable initialized to PTHREAD_ONCE_INIT.                      </span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">   The initialization functions might throw exception which is why        </span></span><br><span class="line"><span class="comment">   this function is not marked with __THROW.  */</span>                          </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_once</span> <span class="params">(<span class="keyword">pthread_once_t</span> *__once_control,                  </span></span></span><br><span class="line"><span class="function"><span class="params">             <span class="keyword">void</span> (*__init_routine) (<span class="keyword">void</span>))</span> __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>, <span class="number">2</span>))</span></span>;</span><br></pre></td></tr></table></figure><p>pthread_once能够保证<code>__init_routine</code>只被调用一次，具体在哪个线程中执行是不定的</p><ul><li>用法:<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">pthread_once_t</span> once=PTHREAD_ONCE_INIT;</span><br><span class="line">&#123;</span><br><span class="line">    ...</span><br><span class="line">    pthread_once(&amp;once,once_init_routine);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li></ul><h2 id="线程私有数据Thread-Specific-Data-TSD"><a href="#线程私有数据Thread-Specific-Data-TSD" class="headerlink" title="线程私有数据Thread Specific Data (TSD)"></a>线程私有数据Thread Specific Data (TSD)</h2><p>在单线程程序中，我们经常使用 “全局变量” 以实现多个函数间共享数据，在多线程环境下，由于数据空间是共享的，因此全局变量也为所有线程所共享。但有时应用程序设计中有必要提供<code>线程私有的全局变量</code>，仅在某个线程中有效，但却可以跨多个函数访问</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Functions for handling thread-specific data.  */</span>                             </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Create a key value identifying a location in the thread-specific             </span></span><br><span class="line"><span class="comment">   data area.  Each thread maintains a distinct thread-specific data            </span></span><br><span class="line"><span class="comment">   area.  DESTR_FUNCTION, if non-NULL, is called with the value                 </span></span><br><span class="line"><span class="comment">   associated to that key when the key is destroyed.                            </span></span><br><span class="line"><span class="comment">   DESTR_FUNCTION is not called if the value associated is NULL when            </span></span><br><span class="line"><span class="comment">   the key is destroyed.  */</span>                                                    </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_key_create</span> <span class="params">(<span class="keyword">pthread_key_t</span> *__key,                            </span></span></span><br><span class="line"><span class="function"><span class="params">                   <span class="keyword">void</span> (*__destr_function) (<span class="keyword">void</span> *))</span>                           </span></span><br><span class="line"><span class="function">     __THROW __<span class="title">nonnull</span> <span class="params">((<span class="number">1</span>))</span></span>;                                                   </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Destroy KEY.  */</span>                                                             </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_key_delete</span> <span class="params">(<span class="keyword">pthread_key_t</span> __key)</span> __THROW</span>;                    </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Return current value of the thread-specific data slot identified by KEY.  */</span></span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">void</span> *<span class="title">pthread_getspecific</span> <span class="params">(<span class="keyword">pthread_key_t</span> __key)</span> __THROW</span>;                 </span><br><span class="line"></span><br><span class="line"><span class="comment">/* Store POINTER in the thread-specific data slot identified by KEY. */</span>         </span><br><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">pthread_setspecific</span> <span class="params">(<span class="keyword">pthread_key_t</span> __key,                            </span></span></span><br><span class="line"><span class="function"><span class="params">                <span class="keyword">const</span> <span class="keyword">void</span> *__pointer)</span> __THROW </span>;</span><br></pre></td></tr></table></figure><h2 id="数据结构"><a href="#数据结构" class="headerlink" title="数据结构"></a>数据结构</h2><blockquote><p>/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h</p></blockquote><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Thread identifiers.  The structure of the attribute type is not             </span></span><br><span class="line"><span class="comment">   exposed on purpose.  */</span>                                                     </span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">unsigned</span> <span class="keyword">long</span> <span class="keyword">int</span> <span class="keyword">pthread_t</span>;                                           </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/* Keys for thread-specific data */</span>                                            </span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">unsigned</span> <span class="keyword">int</span> <span class="keyword">pthread_key_t</span>;                                            </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/* Once-only execution */</span>                                                      </span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">int</span> __ONCE_ALIGNMENT <span class="keyword">pthread_once_t</span>;                                   </span><br><span class="line"></span><br><span class="line"><span class="keyword">union</span> <span class="keyword">pthread_attr_t</span>                            </span><br><span class="line">&#123;                                               </span><br><span class="line">  <span class="keyword">char</span> __size[__SIZEOF_PTHREAD_ATTR_T];         </span><br><span class="line">  <span class="keyword">long</span> <span class="keyword">int</span> __align;                             </span><br><span class="line">&#125;;                                              </span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> __have_pthread_attr_t                   </span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">union</span> <span class="keyword">pthread_attr_t</span> <span class="keyword">pthread_attr_t</span>;    </span><br><span class="line"><span class="meta"># <span class="meta-keyword">define</span> __have_pthread_attr_t 1                </span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span>                                          </span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">union</span>                                   </span><br><span class="line">&#123;                                               </span><br><span class="line">  <span class="class"><span class="keyword">struct</span> __<span class="title">pthread_mutex_s</span> __<span class="title">data</span>;</span>              </span><br><span class="line">  <span class="keyword">char</span> __size[__SIZEOF_PTHREAD_MUTEX_T];        </span><br><span class="line">  <span class="keyword">long</span> <span class="keyword">int</span> __align;                             </span><br><span class="line">&#125; <span class="keyword">pthread_mutex_t</span>;                              </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">union</span>                                   </span><br><span class="line">&#123;                                               </span><br><span class="line">  <span class="class"><span class="keyword">struct</span> __<span class="title">pthread_cond_s</span> __<span class="title">data</span>;</span>               </span><br><span class="line">  <span class="keyword">char</span> __size[__SIZEOF_PTHREAD_COND_T];         </span><br><span class="line">  __extension__ <span class="keyword">long</span> <span class="keyword">long</span> <span class="keyword">int</span> __align;          </span><br><span class="line">&#125; <span class="keyword">pthread_cond_t</span>;</span><br></pre></td></tr></table></figure><h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><ul><li><a href="https://raw.githubusercontent.com/Winddoing/CodeWheel/master/C/pthread/pthread.c" target="_blank" rel="noopener">pthread.c</a></li><li><a href="https://github.com/Winddoing/CodeWheel/tree/master/C/pthread/threadpool" target="_blank" rel="noopener">threadpool</a></li></ul><h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul><li><a href="http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html" target="_blank" rel="noopener">Linux多线程编程（不限Linux)</a></li><li><a href="https://www.ibm.com/developerworks/cn/linux/l-pthred/#ibm-pcon" target="_blank" rel="noopener">pthreads 的基本用法</a></li></ul></div><div class="post-widgets"><div id="needsharebutton-postbottom"><span class="btn"><i class="fa fa-share-alt" aria-hidden="true"></i></span></div></div><div><div style="text-align:center;color:#ccc;font-size:14px">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div><div style="text-align:center;color:#ccc;font-size:16px"><script type="text/javascript" src="https://api.imjad.cn/hitokoto/?cat=&charset=utf-8&length=50&encode=js&fun=sync&source="></script><div id="hitokoto"><script>hitokoto()</script></div></div><div class="reward-container"><div></div> <button disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';"> 打赏</button><div id="qr" style="display:none"><div style="display:inline-block"> <img src="/images/alipay.jpg" alt="Winddoing 支付宝"><p>支付宝</p></div></div></div><div><ul class="post-copyright"><li class="post-copyright-author"> <strong>本文作者：</strong> Winddoing</li><li class="post-copyright-link"> <strong>本文链接：</strong> <a href="http://winddoing.github.io/post/8868.html" title="线程--pthread">http://winddoing.github.io/post/8868.html</a></li><li class="post-copyright-statement"> <strong>作者声明：</strong> 本博文为个人笔记, 由于个人能力有限，难免出现错误，欢迎大家批评指正。</li><li class="post-copyright-license"> <strong>版权声明：</strong> 本博客所有文章除特别声明外，均采用<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i> BY-NC-SA</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags"><a href="/tags/线程/" rel="tag"><i class="fa fa-tag"></i> 线程</a></div><div class="post-nav"><div class="post-nav-item"><a href="/post/54884.html" rel="prev" title="socket错误号"><i class="fa fa-chevron-left"></i> socket错误号</a></div><div class="post-nav-item"> <a href="/post/2578.html" rel="next" title="Android开发相关记录">Android开发相关记录<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments"><div id="lv-container" data-id="city" data-uid="MTAyMC8yOTM5OC81OTY2"></div></div><script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script></div><div class="toggle sidebar-toggle"><span class="toggle-line toggle-line-first"></span><span class="toggle-line toggle-line-middle"></span><span class="toggle-line toggle-line-last"></span></div><aside class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc"> 文章目录</li><li class="sidebar-nav-overview"> 站点概览</li></ul><div class="post-toc-wrap sidebar-panel"><div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#线程"><span class="nav-number">1.</span> <span class="nav-text">线程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用多线程的理由"><span class="nav-number">2.</span> <span class="nav-text">使用多线程的理由</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pthread接口"><span class="nav-number">3.</span> <span class="nav-text">pthread接口</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-create"><span class="nav-number">3.1.</span> <span class="nav-text">pthread_create</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-exit"><span class="nav-number">3.2.</span> <span class="nav-text">pthread_exit</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-join"><span class="nav-number">3.3.</span> <span class="nav-text">pthread_join</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-detach"><span class="nav-number">3.4.</span> <span class="nav-text">pthread_detach</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-self"><span class="nav-number">3.5.</span> <span class="nav-text">pthread_self</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程属性"><span class="nav-number">3.6.</span> <span class="nav-text">线程属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程之间互斥"><span class="nav-number">3.7.</span> <span class="nav-text">线程之间互斥</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程同步"><span class="nav-number">3.8.</span> <span class="nav-text">线程同步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-barrier-xxx"><span class="nav-number">3.9.</span> <span class="nav-text">pthread_barrier_xxx</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pthread-once"><span class="nav-number">3.10.</span> <span class="nav-text">pthread_once</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程私有数据Thread-Specific-Data-TSD"><span class="nav-number">4.</span> <span class="nav-text">线程私有数据Thread Specific Data (TSD)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据结构"><span class="nav-number">5.</span> <span class="nav-text">数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#示例"><span class="nav-number">6.</span> <span class="nav-text">示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div></div><div class="site-overview-wrap sidebar-panel"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" alt="Winddoing" src="/images/Winddoing.jpg"><p class="site-author-name" itemprop="name">Winddoing</p><div class="site-description" itemprop="description">失败缘于忽视细处，成功始于重视小事。</div></div><div class="site-state-wrap motion-element"><nav class="site-state"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">248</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/"><span class="site-state-item-count">57</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/"><span class="site-state-item-count">214</span> <span class="site-state-item-name">标签</span></a></div></nav></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/Winddoing" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Winddoing" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i> GitHub</a></span><span class="links-of-author-item"><a href="https://gitee.com/winddoing" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;winddoing" rel="noopener" target="_blank"><i class="fa fa-fw fa-codiepie"></i> Gitee</a></span><span class="links-of-author-item"><a href="mailto:winddoing@sina.cn" title="E-Mail → mailto:winddoing@sina.cn" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i> E-Mail</a></span><span class="links-of-author-item"><a href="https://stackoverflow.com/users/9567361/winddoing" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;users&#x2F;9567361&#x2F;winddoing" rel="noopener" target="_blank"><i class="fa fa-fw fa-stack-overflow"></i> StackOverflow</a></span><span class="links-of-author-item"><a href="https://travis-ci.org/Winddoing/Winddoing.github.io" title="Travis CI → https:&#x2F;&#x2F;travis-ci.org&#x2F;Winddoing&#x2F;Winddoing.github.io" rel="noopener" target="_blank"><i class="fa fa-fw fa-terminal"></i> Travis CI</a></span></div><div class="cc-license motion-element" itemprop="license"> <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a></div><div class="links-of-blogroll motion-element"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> Links</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"> <a href="https://winddoing.gitbooks.io/embedded_notes/content/" title="https:&#x2F;&#x2F;winddoing.gitbooks.io&#x2F;embedded_notes&#x2F;content&#x2F;" rel="noopener" target="_blank">嵌入式相关</a></li><li class="links-of-blogroll-item"> <a href="http://blog.csdn.net/sdreamq" title="http:&#x2F;&#x2F;blog.csdn.net&#x2F;sdreamq" rel="noopener" target="_blank">CSDN</a></li><li class="links-of-blogroll-item"> <a href="http://www.wowotech.net/" title="http:&#x2F;&#x2F;www.wowotech.net&#x2F;" rel="noopener" target="_blank">蜗窝科技</a></li><li class="links-of-blogroll-item"> <a href="https://blog.csdn.net/xiongxianze" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;xiongxianze" rel="noopener" target="_blank">xiongxianze</a></li></ul></div><div id="days"></div><script>function show_date_time(){window.setTimeout("show_date_time()",1e3),BirthDay=new Date("02/26/2014 15:00:00"),today=new Date,timeold=today.getTime()-BirthDay.getTime(),sectimeold=timeold/1e3,secondsold=Math.floor(sectimeold),msPerDay=864e5,e_daysold=timeold/msPerDay,daysold=Math.floor(e_daysold),e_hrsold=24*(e_daysold-daysold),hrsold=setzero(Math.floor(e_hrsold)),e_minsold=60*(e_hrsold-hrsold),minsold=setzero(Math.floor(60*(e_hrsold-hrsold))),seconds=setzero(Math.floor(60*(e_minsold-minsold))),document.getElementById("days").innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒"}function setzero(e){return e<10&&(e="0"+e),e}show_date_time()</script></div></div></aside><div id="sidebar-dimmer"></div></div></main><footer class="footer"><div class="footer-inner"><div class="copyright"> &copy; 2014 – <span itemprop="copyrightYear">2020</span><span class="with-love" id="heart"><i class="fa fa-heartbeat"></i></span> <span class="author" itemprop="copyrightHolder">Winddoing</span> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-area-chart"></i></span> <span title="站点总字数">652k</span> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-coffee"></i></span> <span title="站点阅读时长">9:53</span></div><div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div> <span class="post-meta-divider">|</span><div class="theme-info">主题 – <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v7.7.0</div><div class="busuanzi-count"><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="post-meta-item" id="busuanzi_container_site_uv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-user"></i></span><span class="site-uv" title="总访客量"><span id="busuanzi_value_site_uv"></span></span></span> <span class="post-meta-divider">|</span><span class="post-meta-item" id="busuanzi_container_site_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span><span class="site-pv" title="总访问量"><span id="busuanzi_value_site_pv"></span></span></span></div><div style="display:inline"><script type="text/javascript">var cnzz_protocol="https:"==document.location.protocol?" https://":" http://";document.write(unescape("%3Cspan id='cnzz_stat_icon_1254703532'%3E%3C/span%3E%3Cscript src='"+cnzz_protocol+"s95.cnzz.com/z_stat.php%3Fid%3D1254703532%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"))</script></div><script>
  function leancloudSelector(url) {
    url = encodeURI(url);
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.getAttribute('id'));
      var title = visitors.getAttribute('data-flag-title');

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .then(() => {
                leancloudSelector(url).innerText = counter.time + 1;
              })
              .catch(error => {
                console.error('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title: title, url: url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.getAttribute('id'));
      });

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url: { '$in': entries } })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length === 0) {
            document.querySelectorAll('.leancloud_visitors .leancloud-visitors-count').forEach(element => {
              element.innerText = 0;
            });
            return;
          }
          for (let item of results) {
            let { url, time } = item;
            leancloudSelector(url).innerText = time;
          }
          for (let url of entries) {
            var element = leancloudSelector(url);
            if (element.innerText == '') {
              element.innerText = 0;
            }
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=Q8qpjA3fOO7FEUBqcmcQFptF-gzGzoHsz')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method: method,
          headers: {
            'X-LC-Id': 'Q8qpjA3fOO7FEUBqcmcQFptF-gzGzoHsz',
            'X-LC-Key': 'tgUTq5bX3fVmn916EMRe65eJ',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script></div></footer></div><script src="/lib/anime.min.js"></script><script src="/lib/velocity/velocity.min.js"></script><script src="/lib/velocity/velocity.ui.min.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script>!function(){var t=document.createElement("script"),e=window.location.protocol.split(":")[0];t.src="https"===e?"https://zz.bdstatic.com/linksubmit/push.js":"http://push.zhanzhang.baidu.com/push.js";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}()</script><script src="/js/local-search.js"></script><script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme: 'forest',
      logLevel: 3,
      flowchart: { curve: 'linear' },
      gantt: { axisFormat: '%m/%d/%Y' },
      sequence: { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script><script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-needmoreshare2@1/needsharebutton.min.js"></script><script>pbOptions={iconStyle:"default",boxForm:"horizontal",position:"bottomCenter",networks:"Weibo,Wechat,QQZone,Twitter,Facebook,Evernote"},new needShareButton("#needsharebutton-postbottom",pbOptions)</script><script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script></body></html>